package com.l.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.l.entity.User;
import com.l.service.ExcelService;
import com.l.utils.ExcelUtil;
import com.l.utils.Msg;

@RestController
public class ExcelController {
	@Autowired
	ExcelService excelService;
	
	//excel导入
	@RequestMapping("/insertUser")
	public Msg insertUser(MultipartFile file){
		if (file.isEmpty()) {
			return Msg.fail();
		}else{
			excelService.insertUser(file);
			return Msg.success();
		}
	}
	//excel导出
	@RequestMapping("/selectUser")
	public Msg selectUser(HttpServletRequest request) throws Exception{
		List<User> userList=excelService.selectUser();
		// 导出到excel
		final String[] USER_RECORES_COLUMNS = new String[] { "姓名_#_5000",
				"余额_#_7000"};
		final String[] USER_RECORES_FIELDS = new String[] { "name",
				"balance"};
		HSSFWorkbook workbook = new HSSFWorkbook();
		ExcelUtil<User> userSheet = new ExcelUtil<User>();
		userSheet.creatAuditSheet(workbook, "data sheet xls", userList,
				USER_RECORES_COLUMNS, USER_RECORES_FIELDS);

		String uuid = System.currentTimeMillis() + "";
		String fileName = "excel/" + uuid + "user.xls";
		String realPath = request.getSession().getServletContext()
				.getRealPath("/excel");
		File file = new File(realPath);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
		}
		FileOutputStream fileOut = new FileOutputStream(file + "/" + uuid
				+ "user.xls");
		workbook.write(fileOut);
		fileOut.close();
		return Msg.success().add("fileName", fileName);
	}
	//下载文件
	@RequestMapping("/download")
	public void download(HttpServletResponse response) throws Exception {
		File file=new File("C:\\Users\\xuejie\\Desktop\\安装方式.txt");
		FileInputStream inputStream=new FileInputStream(file);
		response.setContentType("application/force-download");
		response.addHeader("Content-disposition", "attachment;filename=1.txt");
		OutputStream oStream=response.getOutputStream();
		byte[] buf=new byte[1024];
		int len=0;
		while ((len=inputStream.read(buf))!=-1) {
			oStream.write(buf, 0, len);
		}
	}
}
